<script setup>

import {ref, onMounted, watch, computed} from 'vue';
import axios from "axios";
import {snackbar} from './store'
import moment from 'moment'

// 查询
const pageSize = ref(10);
const pageNo = ref(1)
const headers = [
    {title: 'ID', key: 'id', sortable: false},
    {title: '名称', key: 'name', sortable: false},
    {title: '路线', key: 'route.name', sortable: false},
    {title: '计划开始日期', key: 'startDate', sortable: false},
    {title: '计划结束日期', key: 'endDate', sortable: false},
    {title: '巡更开始日期', key: 'startTime', sortable: false},
    {title: '巡更结束日期', key: 'endTime', sortable: false},
    {title: '周期', key: 'frequency', sortable: false},
    {title: '次数', key: 'count', sortable: false},
    {title: '操作', key: 'actions', sortable: false},
];
const RoleIds = ref([
    { label: "管理员", value: "ADMIN" }
]);
const items = ref([]);
const loading = ref(true);
const totalItems = ref(0);
const isShowDialog = ref(false);
const isShowDeleteDialog = ref(false);
const editedItem = ref({
    userIds: []
});
const dialogType = ref(null)
const dialogEnum = {
    update: '编辑',
    create: '新增'
}
const rules = ref([])
const treeList = ref([]);
const treeUserList = ref([]);
const treeShow = ref(false);

const search = ref('');
const name = ref("");
watch(name, () => {
    search.value = name.value
})
function loadItems({page, itemsPerPage}) {
    loading.value = true;
    pageNo.value = page;
    pageSize.value = itemsPerPage;
    let url = `http://172.168.180.4:7000/patrol-plans?page=${page - 1}&size=${itemsPerPage}`
    if(name.value) {
        url += `&name=${name.value}`
    }
    axios({
        method: "GET",
        url: url,
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
        }
    }).then(res => {}, err => {
        items.value = err.data.content
        totalItems.value = err.data.totalElements
        loading.value = false
    })
}

function clickNew() {
    dialogType.value = dialogEnum.create
    isShowDialog.value = true
    resetEditedItem()
}

function close() {
    isShowDialog.value = false
    resetEditedItem()
    dialogType.value = null
}

function resetEditedItem() {
    editedItem.value = {
        name: "",
        userIds: [],
        notifierIds: [],
        holidayIds: [],
        startTime: "00:00:00",
        endTime: "23:59:59"
    }
}

function save() {
    if(!editedItem.value.count) {
        snackbar.info("次数最小值为1")
        return
    }
    if (dialogType.value === dialogEnum.update) {
        axios({
            method: "PUT",
            url: `http://172.168.180.4:7000/patrol-plans/${editedItem.value.id}`,
            data: editedItem.value,
            headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
            }
        }).then(() => {}, err => {
            snackbar.info('编辑成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: pageSize.value})
        })
    } else if (dialogType.value === dialogEnum.create) {
        axios({
            method: "POST",
            url: `http://172.168.180.4:7000/patrol-plans`,
            data: editedItem.value,
            headers: {
                "Authorization": 'Bearer ' + localStorage.getItem("token")
            }
        }).then((res) => {}, err => {
            if(err.status == 200) {
                snackbar.info('创建成功')
                close()
                loadItems({page: pageNo.value, itemsPerPage: pageSize.value})                
            } else {
                snackbar.info(err.response.data.message)
            }
        })
    }
}

function clickEdit(row) {
    editedItem.value = row
    editedItem.value.holidayIds = row.holidays.map(item => item.id)
    let arr = []
    let notice = []
    row.userIds.forEach(item => {
        treeUserList.value.forEach(k => {
            if(item == k.userId) {
                arr.push(k.title)
            }
        })
    })
    row.notifierIds.forEach(item => {
        treeUserList.value.forEach(k => {
            if(item == k.userId) {
                notice.push(k.title)
            }
        })
    })
    editedItem.value.userNameIds = arr.join(',')
    editedItem.value.noticeName = notice.join(',')
    editedItem.value.routeId = row.route.id
    isShowDialog.value = true
    dialogType.value = dialogEnum.update
}

const beDeleteItem = ref({})

function clickDelete(row) {
    isShowDeleteDialog.value = true
    beDeleteItem.value = row
}

function clickDeleteConfirm() {
    axios({
        method: "DELETE",
        url: `http://172.168.180.4:7000/patrol-plans/${beDeleteItem.value.id}`,
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
        }
    }).then(() => {
        snackbar.info("删除成功")
        loadItems({page: 1, itemsPerPage: pageSize.value})
        clickCloseDelete()
    }, err => {
        snackbar.info("删除成功")
        loadItems({page: 1, itemsPerPage: pageSize.value})
        clickCloseDelete()
    })
}

function clickCloseDelete() {
    isShowDeleteDialog.value = false
    beDeleteItem.value = null
}

const selectAllList = ref(false);
function toggle() {
    if(selectAllList.value) {
        editedItem.value.userIds = []
    } else {
        userList.value.forEach(item => {
            editedItem.value.userIds.push(item.id)
        })
    }
    selectAllList.value = !selectAllList.value
}

const isShowDate = ref(false);
const dateType = ref(0);
const dateSearch = ref(null);
function openDate(val) {
    isShowDate.value = true
    dateType.value = val
    dateSearch.value = moment(new Date()).format('YYYY-MM-DD')
}
function changeDate() {
    if(dateType.value) {
        editedItem.value.endDate = moment(dateSearch.value).format('YYYY-MM-DD')
        isShowDate.value = false
    } else {
        editedItem.value.startDate = moment(dateSearch.value).format('YYYY-MM-DD')
        isShowDate.value = false
    }
}

const holidayList = ref([]);
const routeList = ref([]);
const userList = ref([]);
const frequencyTypeList = ref([
    { id: "CUSTOM_DAY", name: "按日" }
]);

onMounted(() => {
    loadItems({page: 1, itemsPerPage: pageSize.value});
    axios({
        method: "GET",
        url: `http://172.168.180.4:7000/holidays?page=0&size=1000`,
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
        }
    }).then(res => {}, err => {
        holidayList.value = err.data.content
    })
    axios({
        method: "GET",
        url: `http://172.168.180.4:7000/patrol-routes?page=0&size=1000`,
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
        }
    }).then(res => {}, err => {
        routeList.value = err.data.content
    })
    axios({
        method: "GET",
        url: `http://172.168.180.4:7000/users?page=0&size=10000`,
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
        }
    }).then(res => {}, err => {
        userList.value = err.data.content
    })
    axios({
        method: "GET",
        url: "http://172.168.180.4:7000/depts/tree",
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
        }
    }).then(res => {}, err => {
        treeList.value = err.data
        generateList(treeList.value);
        treeUserList.value = treeToArray(treeList.value)
    })
});

// 获取user数组
function treeToArray(tree) {
    let result = [];
    let seenIds = new Set();

    function traverse(node) {
        // Only add the node if its type is 'USER' and its id has not been seen before
        if (node.type === 'USER' && !seenIds.has(node.id)) {
            seenIds.add(node.id);
            result.push({
                id: node.id,
                title: node.title,
                type: node.type,
                userId: node.userId
            });
        }

        // Traverse the children
        if (node.children && node.children.length > 0) {
            node.children.forEach(child => traverse(child));
        }
    }

    // Start the traversal with each root node in the tree
    tree.forEach(node => traverse(node));

    return result;
}

const selectTree = ref([]);
const selectNoticeTree = ref([]);
const checkedKeys = ref([]);
const searchValue = ref("");
const expandedKeys = ref([]);
const autoExpandParent = ref(true);
const dataList = []

watch(searchValue, value => {
  const expanded = dataList
    .map(item => {
      if (item.title.indexOf(value) > -1) {
        return getParentKey(item.key, treeList.value);
      }
      return null;
    })
    .filter((item, i, self) => item && self.indexOf(item) === i);
  expandedKeys.value = expanded;
  searchValue.value = value;
  autoExpandParent.value = true;
});

const generateList = data => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const key = node.key;
    dataList.push({
      key,
      title: key,
    });
    if (node.children) {
      generateList(node.children);
    }
  }
};

const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};

function onExpand(keys) {
    expandedKeys.value = keys;
    autoExpandParent.value = false;
}

function getCheckData(checkedKeys, e) {
    if(treeTitle.value == '请选择巡更人员') {
        selectTree.value = e.checkedNodes
    } else {
        selectNoticeTree.value = e.checkedNodes
    }
}

const treeTitle = ref("");
function openTree() {
    searchValue.value = ""
    expandedKeys.value = []
    autoExpandParent.value = false
    treeShow.value = true
    treeTitle.value = '请选择巡更人员'
    checkedKeys.value = []
    editedItem.value.userIds.forEach(item => {
        treeUserList.value.forEach(k => {
            if(item == k.userId) {
                checkedKeys.value.push(k.id)
            }
        })
    })
    selectTree.value = []
    treeUserList.value.forEach(item => {
        editedItem.value.userIds.forEach(k => {
            if(k == item.userId) {
                selectTree.value.push(item)
            }
        })
    })
}

function openTreeNotice() {
    searchValue.value = ""
    expandedKeys.value = []
    autoExpandParent.value = false
    treeShow.value = true
    treeTitle.value = '请选择通知人员'
    checkedKeys.value = []
    editedItem.value.notifierIds.forEach(item => {
        treeUserList.value.forEach(k => {
            if(item == k.userId) {
                checkedKeys.value.push(k.id)
            }
        })
    })
    selectNoticeTree.value = []
    treeUserList.value.forEach(item => {
        editedItem.value.notifierIds.forEach(k => {
            if(k == item.userId) {
                selectNoticeTree.value.push(item)
            }
        })
    })
}

function saveTree() {
    treeShow.value = false
    if(treeTitle.value == '请选择巡更人员') {
        let arr = []
        editedItem.value.userIds = []
        selectTree.value.forEach(item => {
            if(item.type == 'USER') {
                editedItem.value.userIds.push(item.userId)
                arr.push(item.title)         
            }
        })
        editedItem.value.userNameIds = arr.join(",")        
    } else {
        let arr = []
        editedItem.value.notifierIds = []
        selectNoticeTree.value.forEach(item => {
            if(item.type == 'USER') {
                editedItem.value.notifierIds.push(item.userId)
                arr.push(item.title)         
            }
        })
        editedItem.value.noticeName = arr.join(",")  
    }
}
</script>

<template>
    <v-toolbar density="compact">
        <v-toolbar-title>巡更计划</v-toolbar-title>
        <!-- <v-text-field v-model="name" :clearable="true" hide-details placeholder="计划名称"></v-text-field> -->
        <v-dialog v-model="isShowDialog" max-width="500px">
            <template v-slot:activator="{ props }">
                <v-btn icon="mdi-plus" v-on:click="clickNew" v-bind="props"></v-btn>
            </template>
            <v-card>
                <v-card-title>{{ dialogType }}</v-card-title>
                <v-card-text>
                    <v-text-field v-model="editedItem.name" label="计划名称" required></v-text-field>
                    <v-text-field v-model="editedItem.description" label="描述" required></v-text-field>
                    <v-autocomplete
                    v-model="editedItem.routeId"
                    label="巡更路线"
                    :items=routeList
                    item-title="name"
                    item-value="id"
                    required></v-autocomplete>
                    <v-text-field
                    v-model="editedItem.userNameIds"
                    label="巡更人员"
                    readonly
                    @click="openTree"></v-text-field>
                    <v-text-field
                    v-model="editedItem.noticeName"
                    label="通知人员"
                    readonly
                    @click="openTreeNotice"></v-text-field>
                    <!-- <v-autocomplete
                    v-model="editedItem.userIds"
                    label="巡更人员"
                    :items=userList
                    item-title="name"
                    item-value="id"
                    multiple
                    required>
                        <template v-slot:prepend-item>
                            <v-list-item
                                title="全选"
                                @click="toggle"
                            >
                                <template v-slot:prepend>
                                    <v-checkbox-btn
                                        :model-value="selectAllList"
                                    ></v-checkbox-btn>
                                </template>
                            </v-list-item>
                            <v-divider class="mt-2"></v-divider>
                        </template>
                        <template v-slot:selection="{ item, index }">
                            <v-chip v-if="index < 4">
                                <span>{{ item.title }}</span>
                            </v-chip>
                            <span
                                v-if="index === 4"
                                class="text-grey text-caption align-self-center"
                            >
                                (+{{ editedItem.userIds.length - 4 }} 更多)
                            </span>
                        </template>
                    </v-autocomplete> -->
                    <v-text-field v-model="editedItem.startDate" readonly :clearable="true" label="计划开始日期" @click="openDate(0)"></v-text-field>
                    <v-text-field v-model="editedItem.endDate" readonly :clearable="true" label="计划结束日期" @click="openDate(1)"></v-text-field>   
                    <v-text-field v-model="editedItem.startTime" label="开始时间"></v-text-field>   
                    <v-text-field v-model="editedItem.endTime" label="结束时间"></v-text-field> 
                    <v-select
                    v-model="editedItem.frequencyType"
                    label="周期类型"
                    :items=frequencyTypeList
                    item-title="name"
                    item-value="id"
                    ></v-select>
                    <v-text-field v-model="editedItem.frequency" label="周期值"></v-text-field> 
                    <v-text-field v-model="editedItem.count" label="次数"></v-text-field> 
                    <v-select
                    v-model="editedItem.holidayIds"
                    label="节假日"
                    :items=holidayList
                    item-title="name"
                    item-value="id"
                    multiple
                    ></v-select>  
                </v-card-text>
                <v-dialog v-model="isShowDate" max-width="500px">
                    <v-date-picker v-model="dateSearch" @update:model-value="changeDate"></v-date-picker>
                </v-dialog>
                <v-card-actions>
                    <v-btn color="primary" variant="text" @click="close">关闭</v-btn>
                    <v-btn color="primary" variant="text" @click="save">确定</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>

        
        <v-dialog v-model="treeShow" max-width="500px">
            <v-card>
                <v-card-title class="text-h5">{{ treeTitle }}</v-card-title>
                <v-card-text>
                    <!-- <a-input-search v-model:value="searchValue" style="margin-bottom: 8px" placeholder="搜索" /> -->
                    <a-tree
                    @check="getCheckData"
                    @expand="onExpand"
                    checkable
                    style="width: 100%;"
                    :show-line="true"
                    :tree-data="treeList"
                    :auto-expand-parent="autoExpandParent"
                    :expanded-keys="expandedKeys"
                    v-model:checkedKeys="checkedKeys"
                    :field-names="{
                        label: 'title',
                        key: 'id',
                    }"
                    placeholder="请选择人员"
                    ></a-tree>                      
                </v-card-text>
                <v-card-actions>
                    <v-spacer></v-spacer>
                        <v-btn color="blue-darken-1" variant="text" @click="treeShow = false">取消</v-btn>
                        <v-btn color="blue-darken-1" variant="text" @click="saveTree">确定</v-btn>
                    <v-spacer></v-spacer>
                </v-card-actions>
            </v-card>
        </v-dialog>

        <v-dialog v-model="isShowDeleteDialog" max-width="500px">
            <v-card>
                <v-card-title class="text-h5">删除巡更计划将会删除与之关联的巡更任务和记录。是否确定删除？</v-card-title>
                <v-card-actions>
                    <v-spacer></v-spacer>
                        <v-btn color="blue-darken-1" variant="text" @click="clickCloseDelete">取消</v-btn>
                        <v-btn color="blue-darken-1" variant="text" @click="clickDeleteConfirm">确定</v-btn>
                    <v-spacer></v-spacer>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-toolbar>
  <!--  分页文本待更换   items-per-page-text="每页数量"-->
    <v-data-table-server :search="search" :items-per-page="pageSize" :headers="headers" :items-length="totalItems"
    :items="items"
    :loading="loading"
    class="elevation-1"
    items-per-page-text="每页数量"
    @update:options="loadItems">
        <template v-slot:item.num="{ index }">
            <span>{{ index + 1 }}</span>
        </template>
        <template v-slot:item.actions="{ item }">
            <v-btn icon="mdi-pencil" variant="text" @click="clickEdit(item.raw)"></v-btn>
            <v-btn icon="mdi-delete" variant="text" @click="clickDelete(item.raw)"></v-btn>
        </template>
    </v-data-table-server>
</template>

<style scoped lang="less">

</style>
